<?php

namespace App\Console\Commands\OpenShop\Contract;

use App\Console\Commands\Traits\ExcelCommandTrait;
use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Models\OpenShop\InvestmentPromotion\OpenShopContractTemplateModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserContractModel;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class InitDepositCommand extends Command
{
    use ExcelCommandTrait;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'contract:init-deposit {url?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '初始化定金合同相关数据';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return
     */
    public function handle()
    {
        $url = $this->input->getArgument('url');
        if (!$url) {
            dd('请输入url，全量url：https://file.51kuafu.com/4f/b2/f6ec5ed2e15e28ff0c25f8fce694e777af4c50724e2450439e556f1399d8.xlsx');
        }

        $this->setInputExcel(false)->excelImport(InitDepositCommand::class, $url);
    }

    private array $mainOrders = [];

    public function collection(Collection $collection, ?Command $command)
    {
        $collection->first()->map(function ($item, $row) use ($command) {
            $row = $row + 1;
            if ($row == 1) {
                return null;
            }

            // 常规内容校验
            list($shopCode, $date, $_, $_, $deposit, $_, $skip) = $item;
            $deposit *= 100;

//            if ($skip == '是') {
//
//                // TODO DEBUG
//                return;
//
//                // 把付了钱的单子置为成功
//                $signOrder = OpenShopSignOrderModel::query()->where('shopCode', $shopCode)->first();
//                $signOrder->payPrice = $signOrder->shouldPayPrice;
//                $signOrder->payStatus = SignOrderEnum::PAY_STATUS_OK;
//                $signOrder->save();
//
//                $command->info("{$shopCode} - 跳过，已置为成功");
//
//                return;
//            }

            $shopCode = (int)ltrim($shopCode, 'KF');
            if ($shopCode == 0) {
                return;
            }

//            if ($shopCode < 4327) {
//                return;
//            }

            // 找到主单，+金额
            $signOrder = OpenShopSignOrderModel::query()->where('shopCode', $shopCode)->first();
            if (!$signOrder) {
                $command->error("{$shopCode} 未找到signOrder");
                return;
            }

            $mainProcess = OpenShopMainProcessModel::query()->where('id', $signOrder->mainProcessId)->first();
            if (!$mainProcess) {
                $command->error("{$shopCode} 未找到mainProcess");
                return;
            }

            // 主单
            if ($mainProcess->pid != $mainProcess->id) {
                $mainProcess = OpenShopMainProcessModel::query()->where('id', $mainProcess->pid)->first();
                if (!$mainProcess) {
                    $command->error("{$shopCode} 未找到mainProcessP");
                    return;
                }
            }

            if (!isset($this->mainOrders[$mainProcess->orderNo])) {
                $this->mainOrders[$mainProcess->orderNo] = [
                    'deposit'  => 0,
                    'shopCode' => $shopCode,
                    'family' => [],
                ];
            }

            $this->mainOrders[$mainProcess->orderNo]['deposit'] += $deposit;
            $this->mainOrders[$mainProcess->orderNo]['family'][] = $signOrder->orderNo;

        })->filter();

        // 遍历订单金额
        foreach ($this->mainOrders as $pOrderNo => $arr) {
//            $tail  = $arr['deposit'];
//            $shopCode = $arr['shopCode'];

            $pSignOrder = OpenShopSignOrderModel::query()->where('orderNo', $pOrderNo)->first();
            $pUserContract = OpenShopUserContractModel::query()->where('orderNo', $pOrderNo)->first();

//            $diffPrice = $signOrder->shouldPayPrice - $signOrder->payPrice;

//            if ($diffPrice != $tail) {
//                $command->error("{$shopCode} - {$orderNo} 应付金额不一致；db={$diffPrice} excel={$tail}");
////                continue;
//            }

//            continue;

//            $command->info("{$shopCode} - 稳得一批");



            // 改数据

//            if ($shopCode < 4449) {
//                $signOrder = OpenShopSignOrderModel::query()->where('orderNo', $orderNo)->first();
//
//                $oriShould = $signOrder->shouldPayPrice;
//                $oridecorationDeposit =$userContract->decorationDeposit;
//
//                $signOrder->shouldPayPrice = $signOrder->shouldPayPrice - 500000 * $userContract->shopCount;
//                $signOrder->save();
//
//                $userContract->decorationDeposit = 0;
//                $userContract->save();
//
//                dump($orderNo . ' - ' . $shopCode . ' ' . $oriShould . ' ' . $signOrder->shouldPayPrice . ' ' . $oridecorationDeposit);
//            }

            // 总尾款
            $tailTotal = $pSignOrder->shouldPayPrice - $pSignOrder->payPrice;
            $tailOne = $tailTotal / $pUserContract->shopCount;

            if (!is_int($tailOne)) {
                dd($pOrderNo . ' ' . $tailOne);
            }

            // 所有单子
            foreach ($arr['family'] as $orderNo) {

                /**
                 * 子单 shouldPayPrice = 尾款单店
                 * payPrice = 0
                 *
                 * 主单 shouldPayPrice = 定金 * 店数 + 尾款单店
                 * payPrice = 定金
                 */

                // 主单
                if ($orderNo == $pOrderNo) {
                    $pSignOrder->shouldPayPrice = $pSignOrder->payPrice + $tailOne;
                    $pSignOrder->save();

                    dump("主单 {$orderNo} {$pSignOrder->shouldPayPrice}");
                } else {

                    // 子单
                    $signOrder = OpenShopSignOrderModel::query()->where('orderNo', $orderNo)->first();
                    $signOrder->shouldPayPrice = $tailOne;
                    $signOrder->payPrice = 0;
                    $signOrder->save();

                    dump("子单 {$orderNo} {$signOrder->shouldPayPrice}");

                }
//
//
//                // 存的是多店定金
//                $userContract->depositAmount = $depositAmount;
//                $userContract->mode = OpenShopContractTemplateModel::MODE_3;
//                $userContract->save();
//
//                OpenShopSignOrderModel::query()
//                                      ->where('orderNo', $orderNo)
//                                      ->update(['payStatus' => SignOrderEnum::PAY_STATUS_PART]);

//                $command->info($orderNo . ' ' . $depositAmount);
            }
        }
    }
}
